<script>
import { atLeast, isObject } from '@/utils/kris_utils'
import ApartmentForm from '../ApartmentForm/ApartmentForm.vue'
import { editDorm } from '@/api/dorm'
export default {
  components: {
    ApartmentForm
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default: false
    },
    apartment: {
      required: true,
      default() {
        return {
          address: '',
          number: 1,
          rent: 0,
          photos: []
        }
      }
    }
  },
  data() {
    return {
      form: {
        address: '',
        number: 1,
        rent: 0,
        photos: []
      },
      isSubmitting: false,

      // KRIS:TEMP
      urls: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isActionDisabled() {
      return this.isSubmitting
    },
    isShow() {
      return this.dialogVisible && atLeast(this.apartment, ['address', 'id', 'rent', 'photos'])
    }
  },
  watch: {
    isShow(visible) {
      if (!visible) return

      this.form = { ...this.apartment, photos: [] }
      this.urls = [...this.apartment.photos]
    }
  },
  methods: {
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    handleClose() {
      if (this.isActionDisabled) return
      this.dialogVisible = false
    },
    async handleConfirm() {
      try {
        const flag = await this.$refs.form?.validate()
        if (!flag) return

        this.isSubmitting = true
        await this.sleep(300)

        const params = this.buildParams()
        const result = await editDorm(params)

        if (result.code !== 201) { throw new Error(result?.data?.message ?? '修改失败') }

        this.isSubmitting = false
        this.$emit('success', result)
                this.$refs.form?.resetFields()
      } catch (e) {
        this.isSubmitting = false
        this.$emit('failed', e)
      }
    },
    buildParams() {
      const { address, rent, photos, number } = this.form

      const params = {
        id: this.apartment.id,
        address,
        rent,
        number: 0,
        photo: JSON.stringify(photos)
      }

      return params
    }
  }
}
</script>

<template>
  <div class="create-apartment">
    <el-dialog title="编辑宿舍" :visible.sync="dialogVisible" width="30%" 
    :close-on-click-modal="false" :before-close="handleClose">
      <ApartmentForm ref="form" v-model="form" :disabled="isActionDisabled" :urls="urls" />
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="isSubmitting" @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="isSubmitting" :disabled="isSubmitting" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss"></style>
